package cn.edu.mju.auth.filter;

import cn.edu.mju.common.entity.result.R;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author 16423
 */
public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        System.out.println("=========================================================");
        //1.判断是否为post请求
        if (!"POST".equals(request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        //2.是否为json数据（前端约定格式）
        String contentType = request.getContentType().split(";")[0];
        if (contentType.equals(MediaType.APPLICATION_JSON_VALUE)) {
            //3.从json中获取账号密码进行验证
            try {
                System.out.println();

                //获取数据
                Map<String, String> userInfo = new ObjectMapper().readValue(request.getInputStream(), Map.class);
                String username = userInfo.get(getUsernameParameter());
                String password = userInfo.get(getPasswordParameter());
                String code = userInfo.get("code");
                String uuid = userInfo.get("uuid");

                String  captcha = (String) redisTemplate.opsForValue().get(uuid);

                if (captcha == null){
                    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                    response.getWriter().println(JSONObject.toJSONString(R.error("验证码已过期")));
                    return null;
                }

                if (captcha.equals(code)){
                    //测试数据
                    System.out.println("用户名：" + username + " 密码：" + password);

                    //将明文密码传至下一个filter用于获取jwt
                    response.setHeader("pwd",password);


                    //将前端账号密码传入UsernamePasswordAuthenticationToken验证是否正确
                    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                    setDetails(request, authRequest);
                    return this.getAuthenticationManager().authenticate(authRequest);
                }else {
                    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                    response.getWriter().println(JSONObject.toJSONString(R.error("验证码错误")));
                    return null;
                }


            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
        //使用security默认方式验证，即传统web认证
        return super.attemptAuthentication(request, response);
    }
}
